package com.baiyapeng.code.aspect;

import com.baiyapeng.code.model.TbLog;
import com.baiyapeng.code.service.LogService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * <b>服务层监控切面</b><br/>
 *
 * @author baiyapeng
 * @since 1.0.0
 */
@Aspect
@Component
@Slf4j
public class ServiceAspect {

    @Autowired
    private LogService logService;

    /**
     * <p>监控并写入数据库日志表</p>
     */
    @Around("@annotation(com.baiyapeng.code.aspect.annotation.Monitor)")
    public Object around(ProceedingJoinPoint point) {
        TbLog tbLog = ne TbLog();
        tbLog.setMethodSignature(point.getSignature().toLongString());
        tbLog.setArgsList(Arrays.toString(point.getArgs()));
        tbLog.setCurrTime(System.currentTimeMillis() / 1000);
        log.debug("方法签名：{}", tbLog.getMethodSignature());
        log.debug("方法入参：{}", tbLog.getArgsList());
        Object obj = null;
        try {
            obj = point.proceed();
            log.info("调用成功");
            tbLog.setResult("success");
        } catch (Throwable throwable) {
            log.error("调用失败： {}", throwable.getMessage());
            tbLog.setResult(throwable.getMessage());
            obj = "server error";
        } finally {
            logService.addLog(tbLog);
            return obj;
        }
    }
}
